package com.example.blog_springboot.service;

import com.example.blog_springboot.mapper.BlogMapper;
import com.example.blog_springboot.model.Blog;
import com.example.blog_springboot.model.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service
public class BlogService {
    @Resource
    private BlogMapper blogMapper;

    public List<Blog> selectAll() {
        List<Blog> result = blogMapper.selectAll();
        for (Blog blog : result) {
            String content = blog.getContent();
            if (content.length() > 90){
                blog.setContent(content.substring(0,90) + "...");
            }
        }
        return result;
    }

    public Blog selectOne(String blogId) {
        Blog blog = blogMapper.selectOne(blogId);
        return blog;
    }

    public void add(Blog blog,User user) {
        blog.setUserId(user.getUserId());
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        blogMapper.add(blog);
    }

    public void delete(String blogId, User user) throws Exception {
        Blog blog = blogMapper.selectOne(blogId);
        if (blog.getUserId() != user.getUserId()) {
            throw new Exception();
        }
        blogMapper.delete(blogId);
    }
}